import styled from 'styled-components'
import { useState, useEffect } from 'react'

const Wrapper = styled.div`
  .btn-light {
    width: 31px;
    height: 31px;
  }
  .num {
    display: inline-block;
    width: 31px;
    text-align: center;
  }
`

export default function Counter(props) {
  // 按钮的点击事件处理函数
  const btnHanlder = step => {
    if (props.num + step >= 1) {
      props.onNumChange(props.num + step)
    }
  }

  // 减号按钮的禁用状态
  const [isDisabled, setDisabledState] = useState(false)
  useEffect(() => {
    setDisabledState(props.num <= 1)
  }, [props.num])

  return (
    <Wrapper>
      <button type="button" className="btn btn-light btn-sm" disabled={isDisabled} onClick={() => btnHanlder(-1)}>
        -
      </button>
      <span className="num">{props.num}</span>
      <button type="button" className="btn btn-light btn-sm" onClick={() => btnHanlder(1)}>
        +
      </button>
    </Wrapper>
  )
}
